<template>
  <div class="flex flex-col h-screen">
    <div class="flex flex-1">
      <a-layout-sider
        width="280"
        class="ant-layout-sider-transparent shadow-lg"
      >
        <div class="flex flex-col items-center py-6">
          <div class="text-2xl font-bold mb-8 text-teal-500">个人中心</div>
          <div class="flex">
            <a-avatar
              :src="userAvatar"
              class="mb-4 border-4 border-teal-500 w-32 h-32 hover:bg-gray-200 cursor-pointer"
              size="large"
            />
            <EditOutlined @click="showModal" class="mt-12" />
          </div>

          <!-- 头像的地方 -->
          <a-modal
            v-model:visible="isModalVisible"
            title="更改头像"
            @ok="handleOk"
            @cancel="handleCancel"
          >
            <div class="flex flex-wrap justify-start mb-4">
              <div
                v-for="(preset, index) in presetAvatars"
                :key="index"
                class="avatar-preset m-2  p-1"
                
                @click="selectPreset(preset)"
              >
                <a-avatar :src="preset" class="w-20 h-20 cursor-pointer" :class="{
                  
                  'border-2 border-green-500': currentAvatar == preset
                }" />
              </div>
            </div>

            <input
              type="file"
              accept="image/*"
              @change="handleChange"
              ref="fileInput"
              style="display: none"
            />
            <a-button @click="triggerFileInput">自定义头像</a-button>

            <div v-if="previewImage" class="mt-4">
              <img
                :src="previewImage"
                alt="头像预览"
                class="w-32 h-32 rounded-full"
              />
            </div>
          </a-modal>

          <div
            class="text-lg font-medium mb-2"
            style="
              width: 200px;
              text-align: center;
              overflow: hidden;
              white-space: nowrap;
              text-overflow: ellipsis;
            "
          >
            用户名：{{ userStore.userInfo.username }}
          </div>
          <div
            class="text-md italic mb-4"
            style="
              width: 200px;
              text-align: center;
              overflow: hidden;
              white-space: nowrap;
              text-overflow: ellipsis;
            "
          >
            签名：{{ userStore.userInfo.signature }}
          </div>
          <a-button type="link" @click="openEditModal" class="mb-4">
            编辑资料
          </a-button>
          <a-menu
            mode="inline"
            theme="light"
            :selectedKeys="[activeMenu]"
            @click="handleMenuClick"
            class="w-full bg-transparent"
          >
            <a-menu-item key="settings">
              <SettingOutlined class="mr-2" />
              软件设置
            </a-menu-item>
            <a-menu-item key="about">
              <InfoCircleOutlined class="mr-2" />
              关于我们
            </a-menu-item>
          </a-menu>
        </div>
      </a-layout-sider>

      <a-layout class="flex-1 p-8 flex bg-transparent">
        <div class="w-full max-w-4xl mx-auto">
          <div v-if="activeMenu === 'settings'" class="space-y-6">
            <a-card
              title="设置"
              bordered="false"
              class="ant-card-custom shadow-md"
            >
              <div class="flex flex-col space-y-6">
                <div
                  v-if="userStore.isLoggedIn"
                  class="flex items-center justify-between p-4 rounded shadow"
                >
                  <div class="flex items-center">
                    <a-avatar
                      :src="userAvatar"
                      size="80"
                      class="mr-4 border-2 border-teal-500"
                    />
                    <span class="font-medium text-lg">{{
                      userStore.userInfo.username
                    }}</span>
                  </div>
                  <a-button type="default" @click="handleLogout">
                    退出登录
                  </a-button>
                </div>
                <div v-else class="flex justify-center">
                  <a-button type="primary" @click="handleLogin">
                    登录
                  </a-button>
                </div>

                <div class="flex flex-col space-y-4">
                  <a-card
                    bordered="false"
                    class="p-4 rounded shadow bg-transparent"
                  >
                    <h3 class="text-lg font-semibold mb-2 flex items-center">
                      <SyncOutlined class="mr-2" />
                      数据同步
                    </h3>
                    <div class="flex space-x-4">
                      <a-button
                        type="primary"
                        @click="confirmUpload"
                        :disabled="!userStore.isLoggedIn || uploadLoading"
                        :loading="uploadLoading"
                        class="flex-1"
                      >
                        <UploadOutlined />
                        上传数据至云端
                      </a-button>
                      <a-button
                        type="default"
                        @click="confirmDownload"
                        :disabled="!userStore.isLoggedIn || downloadLoading"
                        :loading="downloadLoading"
                        class="flex-1"
                      >
                        <DownloadOutlined />
                        从云端下载数据
                      </a-button>
                    </div>
                  </a-card>
                </div>
              </div>
            </a-card>
          </div>

          <div v-else-if="activeMenu === 'about'" class="space-y-6">
            <a-card
              title="软件介绍"
              bordered="false"
              class="ant-card-custom shadow-md"
            >
              <div
                class="overflow-auto p-6 rounded shadow"
                style="height: 28rem"
              >
                <p class="mb-4">
                  欢迎使用智联慧动课堂！我们致力于为您提供最佳的学习和管理工具，帮助您高效管理课堂和学生信息。
                </p>
                <div class="flex justify-center mt-4">
                  <a-button type="primary" size="large" @click="goToOtherPage">
                    <InfoCircleOutlined class="mr-2" />
                    关于我们
                  </a-button>
                </div>
              </div>
            </a-card>
          </div>
        </div>
      </a-layout>
    </div>

    <a-modal
      v-model:visible="isLoginModalVisible"
      title="扫码登录"
      :footer="null"
      centered
      class="rounded-lg"
      :maskClosable="false"
    >
      <div class="flex flex-col items-center">
        <a-spin v-if="loginStore.loading" tip="加载中..." class="mb-4" />
        <div v-else class="flex flex-col items-center relative">
          <img
            :src="loginStore.url"
            alt="登录二维码"
            class="w-64 h-64 rounded-lg shadow-md mb-4"
          />
          <a-tooltip title="二维码已过期，点击重新获取">
            <a-icon
              v-if="loginStore.expired"
              :component="ReloadOutlined"
              class="absolute top-2 right-2 text-red-500 cursor-pointer"
              @click="retryQRCode"
              style="font-size: 24px"
            />
          </a-tooltip>
          <p class="text-center text-gray-700">请使用微信扫码关注公众号登录</p>
        </div>
      </div>
    </a-modal>

    <a-modal
      v-model:visible="isEditModalVisible"
      title="编辑资料"
      @ok="saveProfile"
      @cancel="closeEditModal"
      centered
      class="rounded-lg"
    >
      <div class="flex flex-col space-y-4">
        <div class="flex flex-col">
          <label class="mb-1 font-medium">用户名</label>
          <a-input
            v-model:value="editUsername"
            placeholder="请输入用户名"
            maxlength="22"
          />
        </div>
        <div class="flex flex-col">
          <label class="mb-1 font-medium">签名</label>
          <a-input
            v-model:value="editSignature"
            placeholder="请输入签名"
            maxlength="22"
          />
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, watch, onMounted,computed  } from "vue";
import { useRouter } from "vue-router";
import { useUserStore } from "@/stores/user";
import { useLoginStore } from "@/stores/login";
import defaultAvatar from "@/assets/headph1.png";
import avatar1 from "@/assets/headph1.png";
import avatar2 from "@/assets/headph2.png";
import avatar3 from "@/assets/headph3.png";
import avatar4 from "@/assets/headph4.png";
import avatar5 from "@/assets/headph5.png";
import avatar6 from "@/assets/headph6.png";
import avatar7 from "@/assets/headph7.png";
import avatar8 from "@/assets/headph8.png";
import avatar9 from "@/assets/headph9.png";
import { notification, Modal, message } from "ant-design-vue";
import axios from "axios";
import {
  SettingOutlined,
  InfoCircleOutlined,
  SyncOutlined,
  UploadOutlined,
  DownloadOutlined,
  ReloadOutlined,
  EditOutlined,
} from "@ant-design/icons-vue";

const userStore = useUserStore();
const loginStore = useLoginStore();
const router = useRouter();
const { ipcRenderer } = window.electron || {};

const activeMenu = ref("settings");
const userAvatar = computed(() => {
  return userStore.userInfo?.userAvatar || defaultAvatar;
});

const isEditModalVisible = ref(false);
const editUsername = ref(userStore.userInfo.username);
const editSignature = ref(userStore.userInfo.signature);

const isLoginModalVisible = ref(false);

const uploadLoading = ref(false);
const downloadLoading = ref(false);

// -------------------------------------------
const isModalVisible = ref(false);
const previewImage = ref("");
const fileInput = ref(null);
const presetAvatars = ref([
  avatar1,
  avatar2,
  avatar3,
  avatar4,
  avatar5,
  avatar6,
  avatar7,
  avatar8,
  avatar9,
]);

// const loadImageFromLocalStorage = () => {
//   const savedImage = userStore.userInfo.userAvatar
//   if (savedImage) {
//     userAvatar.value = savedImage;
//   }
// };

// 调用函数以加载本地图像
onMounted(() => {
  // userStore.loadUserAvatar()
});
const currentAvatar = ref(defaultAvatar);
const showModal = () => {
  isModalVisible.value = true;
};

const handleOk = () => {
  const username = userStore.userInfo?.username;
  const signature = userStore.userInfo?.signature;
  userStore.updateProfile({
    username,
    signature,
    userAvatar: currentAvatar.value,
  });
  // userStore.setUserAvatar(previewImage.value);
  isModalVisible.value = false;
};

const handleCancel = () => {
  isModalVisible.value = false;
};

const handleChange = (event) => {
  const file = event.target.files[0];
  if (file && file.type.startsWith("image/")) {
    const reader = new FileReader();
    reader.onload = (e) => {
      previewImage.value = e.target.result;
      currentAvatar.value = e.target.result;
    };
    reader.readAsDataURL(file);
  } else {
    message("请选择一张图片文件！");
  }
};

const selectPreset = (preset) => {
  currentAvatar.value = preset;
  previewImage.value = preset;
};

const triggerFileInput = () => {
  fileInput.value.click();
};

const saveProfile = () => {
  if (!editUsername.value.trim()) {
    notification.warning({ message: "用户名不能为空" });
    return;
  }
  userStore.updateProfile({
    username: editUsername.value.trim(),
    signature: editSignature.value.trim(),
    userAvatar: currentAvatar.value
  });
  notification.success({ message: "个人信息已保存" });
  isEditModalVisible.value = false;
};

const openEditModal = () => {
  editUsername.value = userStore.userInfo.username;
  editSignature.value = userStore.userInfo.signature;
  isEditModalVisible.value = true;
};

const closeEditModal = () => {
  isEditModalVisible.value = false;
};

const confirmUpload = () => {
  Modal.confirm({
    title: "确认上传数据",
    content: "您确定要将数据上传至云端吗？",
    onOk: uploadData,
  });
};

const confirmDownload = () => {
  Modal.confirm({
    title: "确认下载数据",
    content: "您确定要从云端下载数据吗？",
    onOk: downloadData,
  });
};

const uploadData = async () => {
  if (!userStore.isLoggedIn) {
    notification.warning({ message: "请先登录" });
    return;
  }
  uploadLoading.value = true;
  notification.info({ message: "正在上传数据中，请稍候..." });
  try {
    const classResponse = await window.electronAPI.getClassData();
    if (!classResponse.success) {
      notification.error({
        message: `获取本地班级数据失败：${classResponse.error}`,
      });
      return;
    }

    const classesData = classResponse.classes.map((cls) => ({
      classNo: cls.class_no,
      className: cls.class_name,
      grade: cls.grade + "",
    }));

    const studentResponse = await window.electronAPI.getStudentData();
    if (!studentResponse.success) {
      notification.error({
        message: `获取学生数据失败：${studentResponse.error}`,
      });
      return;
    }

    const allStudents = studentResponse.students;

    const studentsMap = {};
    allStudents.forEach((student) => {
      if (!studentsMap[student.class_no]) {
        studentsMap[student.class_no] = [];
      }
      studentsMap[student.class_no].push({
        stuNo: student.stu_no,
        stuName: student.stu_name,
        points: student.points,
        attempts: student.attempts,
        corrects: student.corrects,
      });
    });

    const studentsData = classesData.map((cls) => ({
      classNo: cls.classNo,
      students: studentsMap[cls.classNo] || [],
    }));

    const payload = {
      nickname: userStore.userInfo.username,
      signature: userStore.userInfo.signature,
      classesData,
      studentsData,
    };

    const response = await axios.post("http://162.14.66.132/sync", payload, {
      headers: {
        WxToken: userStore.userInfo.token,
      },
    });

    if (response.data && response.data.code == "0") {
      notification.success({ message: "数据已成功上传到云端" });
    } else if (response.status === 401 || response.data.code === 401) {
      handleAuthError();
    } else {
      notification.error({
        message: `上传失败：${response.data.data || "未知错误"}`,
      });
    }
  } catch (error) {
    if (error.response && error.response.status === 401) {
      handleAuthError();
    } else {
      notification.error({ message: `上传失败：${error.message}` });
    }
  } finally {
    uploadLoading.value = false;
  }
};

const downloadData = async () => {
  if (!userStore.isLoggedIn) {
    notification.warning({ message: "请先登录" });
    return;
  }
  downloadLoading.value = true;
  notification.info({ message: "正在同步数据到本地中，请稍候..." });
  try {
    const response = await axios.get(
      "http://162.14.66.132/sync/classes-students",
      {
        headers: {
          WxToken: userStore.userInfo.token,
        },
      }
    );

    if (response.data && response.data.code == "0") {
      const data = response.data.data;
      const flattenedStudents = data.classes.flatMap((cls) =>
        cls.students.map((student) => ({
          ...student,
          stu_no: student.stuNo,
          stu_name: student.stuName,
          class_no: cls.classNo,
        }))
      );

      const classess = data.classes.map((cls) => {
        const { students, ...classInfo } = cls;
        return {
          id: classInfo.id,
          class_name: classInfo.className,
          class_no: classInfo.classNo,
          grade: classInfo.grade,
        };
      });

      const writeResult = await window.electronAPI.writeData({
        classes: classess,
        students: flattenedStudents,
      });

      if (writeResult.success) {
        notification.success({ message: "数据已成功下载并保存到本地" });
      } else {
        notification.error({
          message: `保存本地数据失败：${writeResult.error}`,
        });
      }
    } else if (response.status === 401 || response.data.code === 401) {
      handleAuthError();
    } else {
      notification.error({
        message: `下载失败：${response.data.data || "未知错误"}`,
      });
    }
  } catch (error) {
    if (error.response && error.response.status === 401) {
      handleAuthError();
    } else {
      notification.error({ message: `下载失败：${error.message}` });
    }
  } finally {
    downloadLoading.value = false;
  }
};

const handleAuthError = () => {
  userStore.logout();
  isLoginModalVisible.value = true;
  loginStore.apicode();
  notification.error({ message: "登录已过期，请重新登录" });
};

const handleLogin = () => {
  isLoginModalVisible.value = true;
  loginStore.apicode();
};

const handleLogout = () => {
  loginStore.logout();
};

const retryQRCode = () => {
  loginStore.retryQRCode();
};

const goToOtherPage = () => {
  ipcRenderer.openExternal("http://49.233.250.28/");
};

const handleMenuClick = ({ key }) => {
  activeMenu.value = key;
};

onMounted(() => {
  userStore.initializeUser();
});

watch(
  () => userStore.isLoggedIn,
  (newVal) => {
    if (newVal) {
      isLoginModalVisible.value = false;
    }
  }
);
watch(
  () => isLoginModalVisible.value,
  (newVal) => {
    if (!newVal) {
      loginStore.resetLoginState();
    }
  }
);
watch(
  () => loginStore.error,
  (error) => {
    if (error) {
      isLoginModalVisible.value = false;
      notification.error({ message: "登录失败，请重试" });
    }
  }
);

watch(
  () => userStore.userInfo,
  (newInfo) => {
    editUsername.value = newInfo.username;
    editSignature.value = newInfo.signature;
  },
  { deep: true }
);
</script>

<style scoped>
.ant-layout-sider-transparent {
  background: transparent !important;
}

.ant-menu-item-selected {
  background-color: #e6fffb !important;
  border-left: 4px solid #20c997 !important;
}
.ant-card-custom {
  background: transparent !important;
  border-radius: 12px !important;
}
.ant-btn {
  border-radius: 8px;
}
.ant-modal {
  border-radius: 12px;
}
</style>
